  #include"bufferManager.h"

bufferManager::~bufferManager()
{
	for(int i = 0; i < 100; i++)
		buffer_record[i].DBwrite();
}

int bufferManager::findReplaceBlock()
{	
	int replace_position = 0;
	CTime earliest_time = buffer_record[0].last_use;
	for(int i = 0; i < BUFFERSIZE; i++)
	{
		if(!buffer_record[i].valid)
			break;
		if(earliest_time > buffer_record[i].last_use)
		{
			replace_position = i;
			earliest_time = buffer_record[i].last_use;
		}
	}
	if(i != BUFFERSIZE)
		return i;
	else
		return replace_position;
}

int bufferManager::readBlockFromDisk(CString table_name, int block_position)	//zll:from buffer or disk
{
	CString file=table_name+".rec";
	int i;
	if((i=inBuffer(table_name,block_position))>=0)
		return i;
	int count=findReplaceBlock();
	buffer_record[count].DBwrite();
	buffer_record[count].DBread(file, block_position);
	return count;
}
int bufferManager::inBuffer(CString table_name, int block_position)
{
	CString file=table_name+".rec";
	for(int i=0;i<BUFFERSIZE;i++)
	{
		if(buffer_record[i].inBuffer(file, block_position))
			return i;
	}
	return -1;
}
